using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DataGridViewAutoFilter;
using SpoilsDataSet;

namespace SpoilsInventory
{
    public partial class DeckBuilder : Form
    {

        BindingSource mCardListSource;
        BindingSource mDeckListSource;
        LocalData.DeckDataTable mDeck;
        LocalData.InventoryDisplayDataDataTable mCards;

        public DeckBuilder()
        {
            InitializeComponent();
        }

        private void DeckBuilder_Load(object sender, EventArgs e)
        {

            mDeck = new LocalData.DeckDataTable();

            Common.RefreshInventoryDisplayData();
            mCards = (LocalData.InventoryDisplayDataDataTable)Common.LocalDataSet.InventoryDisplayData.Copy();

            mCardListSource = new BindingSource(mCards,"");
            mDeckListSource = new BindingSource(mDeck, "");

            mCardListSource.CurrentChanged += new EventHandler(mCardListSource_CurrentChanged);
            mDeckListSource.CurrentChanged += new EventHandler(mDeckListSource_CurrentChanged);

            mDeck.RowChanged += new DataRowChangeEventHandler(Deck_RowChanged);
            mDeck.RowDeleted += new DataRowChangeEventHandler(Deck_RowChanged);

            DeckListGrid.BindingContextChanged += new EventHandler(DeckListGrid_BindingContextChanged);
            CardListGrid.BindingContextChanged += new EventHandler(CardListGrid_BindingContextChanged);

            CardListGrid.AutoGenerateColumns = false;

            CardListGrid.ReadOnly = true;
            CardListGrid.Columns[CardListGrid.Columns.Add("Edition", "Edition")].DataPropertyName = "Edition";
            CardListGrid.Columns[CardListGrid.Columns.Add("EditionName", "Edition")].DataPropertyName = "EditionName";
            CardListGrid.Columns[CardListGrid.Columns.Add("CardName", "Name")].DataPropertyName = "CardName";
            CardListGrid.Columns[CardListGrid.Columns.Add("Number", "Number")].DataPropertyName = "Number";

            CardListGrid.Columns[CardListGrid.Columns.Add("Trade", "Trade")].DataPropertyName = "Trade";
            CardListGrid.Columns[CardListGrid.Columns.Add("Rarity", "Rarity")].DataPropertyName = "Rarity";
            CardListGrid.Columns[CardListGrid.Columns.Add("Cost", "Cost")].DataPropertyName = "Cost";
            CardListGrid.Columns[CardListGrid.Columns.Add("Threshold", "Threshold")].DataPropertyName = "Threshold";
            CardListGrid.Columns[CardListGrid.Columns.Add("Type", "Type")].DataPropertyName = "Type";
            CardListGrid.Columns[CardListGrid.Columns.Add("Subtype", "Subtype")].DataPropertyName = "Subtype";
            CardListGrid.Columns[CardListGrid.Columns.Add("Strength", "Strength")].DataPropertyName = "Strength";
            CardListGrid.Columns[CardListGrid.Columns.Add("Life", "Life")].DataPropertyName = "Life";
            CardListGrid.Columns[CardListGrid.Columns.Add("Speed", "Speed")].DataPropertyName = "Speed";

            CardListGrid.Columns[CardListGrid.Columns.Add("NormalCount", "Normal")].DataPropertyName = "NormalCount";
            CardListGrid.Columns[CardListGrid.Columns.Add("FoilCount", "Foil")].DataPropertyName = "FoilCount";
            CardListGrid.Columns[CardListGrid.Columns.Add("Notes", "Notes")].DataPropertyName = "Notes";

            CardListGrid.Sort(CardListGrid.Columns["Edition"], ListSortDirection.Ascending);
            CardListGrid.Columns["Edition"].Visible = false;

            
            CardListGrid.CellFormatting += new DataGridViewCellFormattingEventHandler(Common.FormatGridCell);
            Common.SetGridColumnOrder(Application.StartupPath, this.Name, CardListGrid);
            



            DeckListGrid.AutoGenerateColumns = false;

            DeckListGrid.Columns[DeckListGrid.Columns.Add("Edition", "Edition")].DataPropertyName = "Edition";
            DeckListGrid.Columns[DeckListGrid.Columns.Add("EditionName", "Edition")].DataPropertyName = "EditionName";
            DeckListGrid.Columns[DeckListGrid.Columns.Add("Number", "Number")].DataPropertyName = "Number";
            DeckListGrid.Columns[DeckListGrid.Columns.Add("CardName", "CardName")].DataPropertyName = "CardName";
            DeckListGrid.Columns[DeckListGrid.Columns.Add("Trade", "Trade")].DataPropertyName = "Trade";
            DeckListGrid.Columns[DeckListGrid.Columns.Add("Rarity", "Rarity")].DataPropertyName = "Rarity";
            DeckListGrid.Columns[DeckListGrid.Columns.Add("Cost", "Cost")].DataPropertyName = "Cost";
            DeckListGrid.Columns[DeckListGrid.Columns.Add("Type", "Type")].DataPropertyName = "Type";
            DeckListGrid.Columns[DeckListGrid.Columns.Add("Subtype", "Subtype")].DataPropertyName = "Subtype";
            DeckListGrid.Columns[DeckListGrid.Columns.Add("Threshold", "Threshold")].DataPropertyName = "Threshold";
            DeckListGrid.Columns[DeckListGrid.Columns.Add("Strength", "Strength")].DataPropertyName = "Strength";
            DeckListGrid.Columns[DeckListGrid.Columns.Add("Life", "Life")].DataPropertyName = "Life";
            DeckListGrid.Columns[DeckListGrid.Columns.Add("Speed", "Speed")].DataPropertyName = "Speed";
            DeckListGrid.Columns[DeckListGrid.Columns.Add("NormalCount", "Normal")].DataPropertyName = "NormalCount";
            DeckListGrid.Columns[DeckListGrid.Columns.Add("FoilCount", "Foil")].DataPropertyName = "FoilCount";

            DeckListGrid.Sort(DeckListGrid.Columns["Edition"], ListSortDirection.Ascending);
            DeckListGrid.Columns["Edition"].Visible = false;

            DeckListGrid.CellFormatting += new DataGridViewCellFormattingEventHandler(Common.FormatGridCell);
            Common.SetGridColumnOrder(Application.StartupPath, this.Name, DeckListGrid);

            CardListGrid.DataSource = mCardListSource;
            DeckListGrid.DataSource = mDeckListSource;




            //Temp Code
            //Adds all cards to deck
            //Used to test exports to make sure they work for all cards
            //CardListGrid.Focus();

            //mCardListSource.Position = 0;

            //while (mCardListSource.Position < mCardListSource.Count - 1)
            //{
            //    AddCurrentCard(false, 1, CardListGrid);
            //    mCardListSource.Position += 1;
            //}
          

        }

        void CardListGrid_BindingContextChanged(object sender, EventArgs e)
        {
            CardListGrid.Columns["EditionName"].HeaderCell = new DataGridViewAutoFilterColumnHeaderCell(CardListGrid.Columns["EditionName"].HeaderCell);
            CardListGrid.Columns["Rarity"].HeaderCell = new DataGridViewAutoFilterColumnHeaderCell(CardListGrid.Columns["Rarity"].HeaderCell);
            CardListGrid.Columns["Trade"].HeaderCell = new DataGridViewAutoFilterColumnHeaderCell(CardListGrid.Columns["Trade"].HeaderCell);
            CardListGrid.Columns["Cost"].HeaderCell = new DataGridViewAutoFilterColumnHeaderCell(CardListGrid.Columns["Cost"].HeaderCell);
            CardListGrid.Columns["Threshold"].HeaderCell = new DataGridViewAutoFilterColumnHeaderCell(CardListGrid.Columns["Threshold"].HeaderCell);
            CardListGrid.Columns["Type"].HeaderCell = new DataGridViewAutoFilterColumnHeaderCell(CardListGrid.Columns["Type"].HeaderCell);
            CardListGrid.Columns["Subtype"].HeaderCell = new DataGridViewAutoFilterColumnHeaderCell(CardListGrid.Columns["Subtype"].HeaderCell);
            CardListGrid.Columns["Strength"].HeaderCell = new DataGridViewAutoFilterColumnHeaderCell(CardListGrid.Columns["Strength"].HeaderCell);
            CardListGrid.Columns["Life"].HeaderCell = new DataGridViewAutoFilterColumnHeaderCell(CardListGrid.Columns["Life"].HeaderCell);
            CardListGrid.Columns["Speed"].HeaderCell = new DataGridViewAutoFilterColumnHeaderCell(CardListGrid.Columns["Speed"].HeaderCell);
        }

        void DeckListGrid_BindingContextChanged(object sender, EventArgs e)
        {
            DeckListGrid.Columns["EditionName"].HeaderCell = new DataGridViewAutoFilterColumnHeaderCell(DeckListGrid.Columns["EditionName"].HeaderCell);
            DeckListGrid.Columns["Rarity"].HeaderCell = new DataGridViewAutoFilterColumnHeaderCell(DeckListGrid.Columns["Rarity"].HeaderCell);
            DeckListGrid.Columns["Cost"].HeaderCell = new DataGridViewAutoFilterColumnHeaderCell(DeckListGrid.Columns["Cost"].HeaderCell);
            DeckListGrid.Columns["Trade"].HeaderCell = new DataGridViewAutoFilterColumnHeaderCell(DeckListGrid.Columns["Trade"].HeaderCell);
            DeckListGrid.Columns["Type"].HeaderCell = new DataGridViewAutoFilterColumnHeaderCell(DeckListGrid.Columns["Type"].HeaderCell);
            DeckListGrid.Columns["Subtype"].HeaderCell = new DataGridViewAutoFilterColumnHeaderCell(DeckListGrid.Columns["Subtype"].HeaderCell);
            DeckListGrid.Columns["Threshold"].HeaderCell = new DataGridViewAutoFilterColumnHeaderCell(DeckListGrid.Columns["Threshold"].HeaderCell);
            DeckListGrid.Columns["Strength"].HeaderCell = new DataGridViewAutoFilterColumnHeaderCell(DeckListGrid.Columns["Strength"].HeaderCell);
            DeckListGrid.Columns["Life"].HeaderCell = new DataGridViewAutoFilterColumnHeaderCell(DeckListGrid.Columns["Life"].HeaderCell);
            DeckListGrid.Columns["Speed"].HeaderCell = new DataGridViewAutoFilterColumnHeaderCell(DeckListGrid.Columns["Speed"].HeaderCell);
        }



        void mDeckListSource_CurrentChanged(object sender, EventArgs e)
        {
            if (mDeckListSource.Current != null)
            {


                LocalData.DeckRow aRow = (LocalData.DeckRow)((DataRowView)mDeckListSource.Current).Row;

                if (aRow.IsNull("Edition"))
                    return;

                string aFileName = Common.ImagePath(Application.StartupPath, aRow.Edition, aRow.CardName);

                if (System.IO.File.Exists(aFileName))
                    DeckPictureBox.Image = Image.FromFile(aFileName);
                else
                    DeckPictureBox.Image = null;
            }
            else
            {
                DeckPictureBox.Image = null;
            }
        }

        void mCardListSource_CurrentChanged(object sender, EventArgs e)
        {

            if (mCardListSource.Current != null)
            {

                LocalData.InventoryDisplayDataRow aRow = (LocalData.InventoryDisplayDataRow)((DataRowView)mCardListSource.Current).Row;

                if (aRow.IsNull("Edition"))
                    return;

                string aFileName = Common.ImagePath(Application.StartupPath, aRow.Edition, aRow.CardName);

                if (System.IO.File.Exists(aFileName))
                    CardListPictureBox.Image = Image.FromFile(aFileName);
                else
                    CardListPictureBox.Image = null;
            }
            else
            {
                CardListPictureBox.Image = null;
            }
        }

        void Deck_RowChanged(object sender, DataRowChangeEventArgs e)
        {
           
            mDeckChangedSinceLoad = true;
            RefreshDeckStats();
        }






        private void CardListGrid_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            
            bool aFoil = false;
            int aIncrement = 1;



            if ((Control.ModifierKeys & Keys.Shift) == Keys.Shift)
                aIncrement *= 4;
            else
                if ((Control.ModifierKeys & Keys.Control) == Keys.Control)
                    aIncrement *= 2;

            if (e.Button == MouseButtons.Right)
                aFoil = true;


            AddCurrentCard(aFoil, aIncrement);
           
        }

        private void DeckListGrid_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            bool aFoil = false;
            int aIncrement = -1;



            if ((Control.ModifierKeys & Keys.Shift) == Keys.Shift)
                aIncrement *= 4;
            else
                if ((Control.ModifierKeys & Keys.Control) == Keys.Control)
                    aIncrement *= 2;

            if (e.Button == MouseButtons.Right)
                aFoil = true;


            AddCurrentCard(aFoil, aIncrement,DeckListGrid);
        }

        private void AddCurrentCard(bool isFoil, int theIncrement)
        {
            AddCurrentCard(isFoil, theIncrement, CardListGrid);
        }

        private void AddCurrentCard(bool isFoil, int theIncrement, DataGridView theGrid)
        {
            int aEdition = (int)theGrid.CurrentRow.Cells["Edition"].Value;
            int aNumber = (int)theGrid.CurrentRow.Cells["Number"].Value;
            int aNormalIncrement = 0;
            int aFoilIncrement = 0;

            if (isFoil)
                aFoilIncrement = theIncrement;
            else
                aNormalIncrement = theIncrement;

            LocalData.InventoryDisplayDataRow aCardRow = mCards.FindByEditionNumber(aEdition, aNumber);

            LocalData.DeckRow aDeckRow = mDeck.FindByEditionNumber(aCardRow.Edition, aCardRow.Number);
            if (aDeckRow == null)
            {

                aDeckRow = mDeck.AddDeckRow(aCardRow.Edition, aCardRow.EditionName, aCardRow.Number, aCardRow.CardName, aCardRow.Trade,aCardRow.Cost, aCardRow.Rarity, aCardRow.Type, aCardRow.Subtype,aCardRow.Threshold,aCardRow.Strength, aCardRow.Life, aCardRow.Speed, aNormalIncrement, aFoilIncrement);
            }
            else
            {
                if (!(aDeckRow.NormalCount + aDeckRow.FoilCount + aNormalIncrement + aFoilIncrement > 4)  || aDeckRow.Edition == Common.STAPLE_RESOURCE)
                {
                    aDeckRow.NormalCount += aNormalIncrement;
                    aDeckRow.FoilCount += aFoilIncrement;
                }
                else
                {
                    System.Media.SystemSounds.Hand.Play();
                }
            }

            if (aDeckRow.NormalCount < 0)
                aDeckRow.NormalCount = 0;
            else
                if (CheckInventoryCheckbox.Checked && aDeckRow.NormalCount > aCardRow.NormalCount && aDeckRow.Edition != 999)
                {
                    System.Media.SystemSounds.Hand.Play();
                    aDeckRow.NormalCount = aCardRow.NormalCount;
                }

                

            if (aDeckRow.FoilCount < 0)
                aDeckRow.FoilCount = 0;
            else
                if (CheckInventoryCheckbox.Checked && aDeckRow.FoilCount > aCardRow.FoilCount && aDeckRow.Edition != 999)
                {
                    System.Media.SystemSounds.Hand.Play();
                    aDeckRow.FoilCount = aCardRow.FoilCount;
                }

            if (aDeckRow.NormalCount == 0 && aDeckRow.FoilCount == 0)
                mDeck.RemoveDeckRow(aDeckRow);
        }

        private void CardListGrid_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Add || e.KeyCode == Keys.Subtract)
            {
                int aIncrement = 1;
                bool aFoil = false;

                if (e.KeyCode == Keys.Subtract)
                    aIncrement = -1;

                if (e.Alt)
                    aFoil = true;

                if (e.Shift)
                    aIncrement *= 4;
                else
                    if (e.Control)
                        aIncrement *= 2;

                AddCurrentCard(aFoil, aIncrement);
            }


        }


        private void FindInventoryCardNameTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                TextBox aTextbox = (TextBox)sender;

                DataRow[] aRows = Common.LocalDataSet.Card.Select("Name Like '" + aTextbox.Text + "%'");
                if (aRows.Length == 0)
                    return;
                LocalData.InventoryDisplayDataRow aCardRow = mCards.FindByEditionNumber((int)aRows[0]["Edition"], (int)aRows[0]["Number"]);

                for (int i = 0; i < mCardListSource.Count; i++)
                {
                    if (((DataRowView)mCardListSource[i]).Row == aCardRow)
                    {
                        mCardListSource.Position = i;
                        break;
                    }
                }

                aTextbox.SelectAll();
            }
        }


        private void FindInventoryCardTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                TextBox aTextbox = (TextBox)sender;

                string aEditionNumber = aTextbox.Text.Substring(0, 1);
                string aEdition = Common.LocalDataSet.Editions.FindByNumber(Convert.ToInt32(aEditionNumber)).Name;



                string aCardNumber = aTextbox.Text.Replace("+", "").Substring(1, aTextbox.Text.Length - 1);



                LocalData.InventoryDisplayDataRow aCardRow = mCards.FindByEditionNumber(Convert.ToInt32(aEditionNumber), Convert.ToInt32(aCardNumber));
                for (int i = 0; i < mCardListSource.Count; i++)
                {
                    if (((DataRowView)mCardListSource[i]).Row == aCardRow)
                    {
                        mCardListSource.Position = i;
                        break;
                    }
                }

                aTextbox.SelectAll();
            }
        }

        private void RefreshDeckStats()
        {
            int aCharacters = Convert.ToInt32(Common.IsNull(mDeck.Compute("Sum(NormalCount) + Sum(FoilCount)", "Type='Character' and Type<>'Faction'"),0));
            int aTactics = Convert.ToInt32(Common.IsNull(mDeck.Compute("Sum(NormalCount) + Sum(FoilCount)", "Type='Tactic' and Type<>'Faction'"), 0));
            int aItems = Convert.ToInt32(Common.IsNull(mDeck.Compute("Sum(NormalCount) + Sum(FoilCount)", "Type='Item' and Type<>'Faction'"), 0));
            int aLocations = Convert.ToInt32(Common.IsNull(mDeck.Compute("Sum(NormalCount) + Sum(FoilCount)", "Type='Location' and Type<>'Faction'"), 0));
            int aResources = Convert.ToInt32(Common.IsNull(mDeck.Compute("Sum(NormalCount) + Sum(FoilCount)", "Type='Resource' and Type<>'Faction'"), 0));
            int aTotal = Convert.ToInt32(Common.IsNull(mDeck.Compute("Sum(NormalCount) + Sum(FoilCount)", "Type<>'Faction'"), 0));



            CharacterValueLabel.Text = aCharacters.ToString() + " (" + Common.IsNull(((((double)aCharacters) / ((double)aTotal)) * 100),0).ToString() + "%)" ;
            TacticValueLabel.Text = aTactics.ToString() + " (" + Common.IsNull(((((double)aTactics) / ((double)aTotal)) * 100),0).ToString() + "%)";
            ItemValueLabel.Text = aItems.ToString() + " (" + Common.IsNull(((((double)aItems) / ((double)aTotal)) * 100),0).ToString() + "%)";
            LocationValueLabel.Text = aLocations.ToString() + " (" + Common.IsNull(((((double)aLocations) / ((double)aTotal)) * 100),0).ToString() + "%)";
            ResourceValueLabel.Text = aResources.ToString() + " (" + Common.IsNull(((((double)aResources) / ((double)aTotal)) * 100), 0).ToString() + "%)";

            QuickStatCharactersLabel.Text = "Characters: " + CharacterValueLabel.Text;
            QuickStatTacticsLabel.Text = "Tactics: " + TacticValueLabel.Text;
            QuickStatItemsLabel.Text = "Items: " + ItemValueLabel.Text;
            QuickStatLocationsLabel.Text = "Locations: " + LocationValueLabel.Text;
            QuickStatResourcesLabel.Text = "Resources: " + ResourceValueLabel.Text;
            QuickStatCardCountLabel.Text = "Card Count: " + aTotal.ToString();

            TotalValueLabel.Text = aTotal.ToString();

            string aFirstRCODChance = Math.Round((((double)aResources) / ((double)aTotal)) * 8, 2).ToString();
            string aSecondRCODChance = Math.Round((((double)aResources) / ((double)aTotal)) * 9, 2).ToString();
            RCODLabel.Text = "RCOD: " + aFirstRCODChance + " (" + aSecondRCODChance + ")";
        }

        private void SaveDeckButton_Click(object sender, EventArgs e)
        {
           SaveDeck();
        }

        private bool SaveDeck()
        {
            SaveFileDialog aFileDialog = new SaveFileDialog();
            aFileDialog.Filter = "XML Files (*.xml)|*.xml";
            aFileDialog.DefaultExt = "xml";

            if (aFileDialog.ShowDialog() == DialogResult.OK)
            {

                string aDeleteFileName = "";

                if (System.IO.File.Exists(aFileDialog.FileName))
                {

                    aDeleteFileName = System.IO.Path.GetTempFileName();
                    System.IO.File.Delete(aDeleteFileName);
                    System.IO.File.Move(aFileDialog.FileName, aDeleteFileName);

                }

                try
                {
                    mDeck.WriteXml(aFileDialog.FileName, XmlWriteMode.WriteSchema);

                    if (aDeleteFileName != "")
                        System.IO.File.Delete(aDeleteFileName);

                    mDeckChangedSinceLoad = false;
                    return true;

                }
                catch
                {
                    if (aDeleteFileName != "")
                        System.IO.File.Move(aDeleteFileName, aFileDialog.FileName);

                    return false;
                }

            }
            else
            {
                return false;
            }
        }

        private void ExportOCTGNDeck()
        {
            StringBuilder aOCTGNDeck = new StringBuilder();

            string aOCTGNStyleSheet = Common.GetAppSetting(Application.StartupPath,"OCTGNStylesheet");
            if(aOCTGNStyleSheet == "")
            {
            OpenFileDialog aOpenDialog = new OpenFileDialog();
            aOpenDialog.Filter = "OCTGN Deck Stylesheet (Decklist.xsl)|Decklist.xsl";
            aOpenDialog.Title = "Please locate the Stylesheet file (usually located in the 'db' folder in your OCTGN folder.)";
            if(aOpenDialog.ShowDialog() != DialogResult.OK)
                return;
            else
            {
                Common.SetAppSetting(Application.StartupPath, "OCTGNStylesheet", aOpenDialog.FileName);
                aOCTGNStyleSheet = aOpenDialog.FileName;
            }
            }
            

            aOCTGNDeck.Append(@"<?xml version=""1.0""?>");
            aOCTGNDeck.Append(System.Environment.NewLine);
            aOCTGNDeck.Append(@"<?xml-stylesheet type=""text/xsl"" href=""" + aOCTGNStyleSheet + @"""?>");
            aOCTGNDeck.Append(System.Environment.NewLine);
            aOCTGNDeck.Append(@"<OCTGNDeck Version=""1.0""><header><charset codepage=""1252""/></header><deck><deckinfo><title>SpoilsInventoryExport</title><decktypeid>0</decktypeid><creator></creator><version></version><description></description><email></email><comments></comments></deckinfo><maindeck>");

            foreach (LocalData.DeckRow aRow in mDeck)
            {
                for (int i = 0; i < aRow.NormalCount + aRow.FoilCount; i++)
                {
                    string aCardName = aRow.CardName;

                    if(aCardName == "Mau Consultant")
                        aCardName = @"Mau ""Consultant""";

                    if(aCardName == "Voidal Perversion")
                        aCardName = "Voidal Perversion.";

                    if(aCardName == "Ritual of the Knob & Pull")
                        aCardName = "Ritual of the Knob &amp; Pull";

                    if(aCardName == "First Unified Market of Abstract Secure Theoreticals")
                        aCardName = "F.U.M.A.S.T.";



                    aOCTGNDeck.Append(@"<card id=""-1"">" + aCardName + "</card>");
                }
            }

            aOCTGNDeck.Append("</maindeck><sideboard/></deck></OCTGNDeck>");


            SaveFileDialog aSaveDialog = new SaveFileDialog();
            aSaveDialog.Filter = "OCTGN Deck File (*.xml)|*.xml";
            aSaveDialog.DefaultExt = "xml";
            if (aSaveDialog.ShowDialog() == DialogResult.OK)
            {
                System.IO.StreamWriter aWriter = new System.IO.StreamWriter(aSaveDialog.FileName);
                aWriter.Write(aOCTGNDeck.ToString());
                aWriter.Close();
            }
        }


        private bool mDeckChangedSinceLoad = false;
        private void LoadDeckButton_Click(object sender, EventArgs e)
        {
            if (mDeckChangedSinceLoad)
            {
                DialogResult aMessageResult = MessageBox.Show("The current deck has changed since it was last saved.  Do you want to save it before loading a new one?", "Save?", MessageBoxButtons.YesNoCancel);
                if (aMessageResult == DialogResult.Yes)
                    if (!SaveDeck())
                        return;
                if (aMessageResult == DialogResult.Cancel)
                    return;
            }
                OpenFileDialog aFileDialog = new OpenFileDialog();
                aFileDialog.Filter = "XML Files (*.xml)|*.xml";
                aFileDialog.DefaultExt = "xml";

                if (aFileDialog.ShowDialog() == DialogResult.OK)
                {
                    LocalData.DeckDataTable aBackup = (LocalData.DeckDataTable)mDeck.Copy();
                    try
                    {
                        mDeck.Clear();
                        mDeck.ReadXml(aFileDialog.FileName);
                    }
                    catch(Exception ex)
                    {
                        MessageBox.Show("Could not load deck." + System.Environment.NewLine + System.Environment.NewLine + ex.Message);
                        mDeck.Merge(aBackup);
                    }
                }

            
        }

        private void DeckBuilder_Resize(object sender, EventArgs e)
        {
            CardListPictureBox.Height = splitContainer2.Height / 2;
            DeckPictureBox.Height = splitContainer2.Height / 2;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ExportOCTGNDeck();
        }

        private void lookupOnAthenaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.ActiveControl is DataGridView)
                {
                    DataGridView aGrid = (DataGridView)this.ActiveControl;

                    LocalData.CardRow aCardRow = Common.LocalDataSet.Card.FindByEditionNumber((int)aGrid.Rows[aGrid.CurrentCell.RowIndex].Cells["Edition"].Value, (int)aGrid.Rows[aGrid.CurrentCell.RowIndex].Cells["Number"].Value);
                    string aCardName = aCardRow.Name.Replace(" ", "+");
                    System.Diagnostics.Process.Start("http://www.metatime.net/athena/search.php?exact=" + aCardName);
                }
            }
            catch { }
        }

        private void reorderGridColumnsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            GridColumnOrder aColumnOrderForm = new GridColumnOrder(this.Name, aClickedGrid);
            aColumnOrderForm.ShowDialog();
        }

        DataGridView aClickedGrid; //This is a hack, since ActiveControl isn't working becuase the grid is readonly
        private void Grids_CellContextMenuStripNeeded(object sender, DataGridViewCellContextMenuStripNeededEventArgs e)
        {
            DataGridView aGrid = (DataGridView)sender;
            aGrid.Focus();
            try
            {
                aGrid.CurrentCell = aGrid.Rows[e.RowIndex].Cells[e.ColumnIndex];
            }
            catch { }

            if (aGrid == DeckListGrid)
            {
                RefreshSeparator.Visible = true;
                refreshCardDataToolStripMenuItem.Visible = true;
            }
            else
            {
                RefreshSeparator.Visible = false;
                refreshCardDataToolStripMenuItem.Visible = false;
            }


            aClickedGrid = aGrid;

        }

        private void refreshCardDataToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (aClickedGrid == DeckListGrid)
            {
                LocalData.DeckDataTable aDeckCopy = (LocalData.DeckDataTable)mDeck.Copy();

                mDeck.Clear();

                foreach (LocalData.DeckRow aRow in aDeckCopy)
                {
                    LocalData.CardRow aCardRow = Common.LocalDataSet.Card.FindByEditionNumber(aRow.Edition, aRow.Number);

                    mDeck.AddDeckRow(aCardRow.Edition, aCardRow.EditionsRow.Name, aCardRow.Number, aCardRow.Name, aCardRow.Trade, aCardRow.Cost, aCardRow.Rarity, aCardRow.Type, aCardRow.Subtype, aCardRow.Threshold, aCardRow.Strength, aCardRow.Life, aCardRow.Speed, aRow.NormalCount, aRow.FoilCount);

                }
            }
        }

        private void ExportMWSButton_Click(object sender, EventArgs e)
        {
            ExportMWSDeck();
        }

        private void ExportMWSDeck()
        {
            StringBuilder aMWSDeck = new StringBuilder();

            //string aOCTGNStyleSheet = Common.GetAppSetting(Application.StartupPath, "OCTGNStylesheet");
            //if (aOCTGNStyleSheet == "")
            //{
            //    OpenFileDialog aOpenDialog = new OpenFileDialog();
            //    aOpenDialog.Filter = "OCTGN Deck Stylesheet (Decklist.xsl)|Decklist.xsl";
            //    aOpenDialog.Title = "Please locate the Stylesheet file (usually located in the 'db' folder in your OCTGN folder.)";
            //    if (aOpenDialog.ShowDialog() != DialogResult.OK)
            //        return;
            //    else
            //    {
            //        Common.SetAppSetting(Application.StartupPath, "OCTGNStylesheet", aOpenDialog.FileName);
            //        aOCTGNStyleSheet = aOpenDialog.FileName;
            //    }
            //}


            //aMWSDeck.Append(@"<?xml version=""1.0""?>");
            //aMWSDeck.Append(System.Environment.NewLine);
            //aMWSDeck.Append(@"<?xml-stylesheet type=""text/xsl"" href=""" + aOCTGNStyleSheet + @"""?>");
            //aMWSDeck.Append(System.Environment.NewLine);
            //aMWSDeck.Append(@"<OCTGNDeck Version=""1.0""><header><charset codepage=""1252""/></header><deck><deckinfo><title>SpoilsInventoryExport</title><decktypeid>0</decktypeid><creator></creator><version></version><description></description><email></email><comments></comments></deckinfo><maindeck>");

            foreach (LocalData.DeckRow aRow in mDeck)
            {

                aMWSDeck.Append(aRow.NormalCount.ToString());
                aMWSDeck.Append(" [");
                aMWSDeck.Append(Common.LocalDataSet.Editions.FindByNumber(aRow.Edition).Name);
                aMWSDeck.Append("] ");
                if (aRow.CardName == "Mau Consultant")
                    aMWSDeck.Append("Mau 'Consultant'");
                else
                    aMWSDeck.Append(aRow.CardName);
                aMWSDeck.Append(System.Environment.NewLine);
                //for (int i = 0; i < aRow.NormalCount + aRow.FoilCount; i++)
                //{
                //    aMWSDeck.Append(@"<card id=""-1"">" + aRow.CardName + "</card>");
                //}
            }

            //aMWSDeck.Append("</maindeck><sideboard/></deck></OCTGNDeck>");


            SaveFileDialog aSaveDialog = new SaveFileDialog();
            aSaveDialog.Filter = "MWS Deck File (*.mwDeck)|*.mwDeck";
            aSaveDialog.DefaultExt = "mwDeck";
            if (aSaveDialog.ShowDialog() == DialogResult.OK)
            {
                System.IO.StreamWriter aWriter = new System.IO.StreamWriter(aSaveDialog.FileName);
                aWriter.Write(aMWSDeck.ToString());
                aWriter.Close();
            }
        }


       


    }
}